from service.strategy_service import Strategy
from utils import statisticalutil, parse_util


class StrategyAve(Strategy):
    def __init__(self, name, data):
        super().__init__(name, data)
        self.ave_num = 0

    # 均线策略
    def execute(self):
        self.break_ave()

    # 突破均线
    def break_ave(self):
        if not self.check_params():
            return

    # 检查参数
    def check_params(self):
        if self.ave_num == 0:
            self.resp('500', '未输入均线天数')
            return False
        return True


# 实时触发
class StrategyAveRt(StrategyAve):
    def __init__(self, name, data):
        super().__init__(name, data)
        self.rt_price = 0
        self.ks = None  # 最新的K线 倒叙
        self.ave = 0
        self.key = 'sp'

    def check_params(self):
        if not super().check_params():
            return False
        if self.rt_price == 0 or self.ks is None:
            self.resp('500', '参数错误')
            return False
        if len(self.ks) < self.ave_num:
            self.resp('500', '参数错误')
            return False
        return True

    def break_ave(self):
        super().break_ave()
        self.ave = statisticalutil.mean(parse_util.list_dict_to_list(self.ks[-self.ave_num:], self.key))
        if self.rt_price >= self.ave:
            return True
        return False
